using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using viBook.Common;
using viBook.Filters;
using viBook.Models;
using viBook.Repositories;

namespace viBook.Controllers
{
    public class ChaptersController : BaseController
    {
        #region Constructors and Repository vars

        private readonly IActivityRepository _activityRepository;
        private readonly IChapterRepository _chapterRepository;

        public ChaptersController(IChapterRepository chapterRepository, IActivityRepository activityRepository)
        {
            _chapterRepository = chapterRepository;
            _activityRepository = activityRepository;
        }

        #endregion

        public ViewResult Details(int id)
        {
            Chapter chapter = _chapterRepository.Find(id, ExtendedIdentity.Id);
            ViewBag.IsOwner = ExtendedIdentity.Id != 0 && ExtendedIdentity.Id == chapter.Book.UploadedBy;
            return View(chapter);
        }


        public ActionResult Create(int bookid)
        {
            var chapter = new Chapter {BookId = bookid, Pages = new List<Page>()};
            return View(chapter);
        }

        [HttpPost]
        public ActionResult Create(Chapter chapter)
        {
            if (!string.IsNullOrEmpty(chapter.ChapterName))
            {
                if (_chapterRepository.All.Any(c => c.ChapterName.ToLower().Equals(chapter.ChapterName.ToLower().Trim()) && chapter.Id != chapter.Id))
                    ModelState.AddModelError("ChapterName", "ChapterName already exists.");
            }
            chapter.Pages = new List<Page>();
            if (ModelState.IsValid)
            {
               
                string images = Request["fileUploadInfo"];
                string[] listImage = images.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string image in listImage)
                {
                    if (!string.IsNullOrEmpty(image))
                    {
                        string imagepath = image.Replace(Server.MapPath("~"), "/").Replace("\\", "/");
                        //add the first image of list image become chapterimg
                        if (string.IsNullOrEmpty(chapter.ChapterImage))
                            chapter.ChapterImage = imagepath;

                        chapter.Pages.Add(new Page
                                              {
                                                  ImageSource = imagepath
                                              });
                    }
                }
                chapter.NumberOfPages = chapter.Pages.Count;
                _chapterRepository.InsertOrUpdate(chapter);
                //_chapterRepository.Save();-saved at respository

                return RedirectToAction("Details", "Books", new { id = chapter.BookId });
            }
            return View(chapter);
        }

        public ActionResult Edit(int id)
        {
            return View(_chapterRepository.Find(id, ExtendedIdentity.Id));
        }

        // TODO
        [HttpPost]
        public ActionResult Edit(Chapter chapter)
        {

            if (!string.IsNullOrEmpty(chapter.ChapterName))
            {
                if(_chapterRepository.All.Any(c=>c.ChapterName.ToLower().Equals(chapter.ChapterName.ToLower().Trim())&& chapter.Id!=chapter.Id))
                    ModelState.AddModelError("ChapterName", "ChapterName already exists.");
            }
            if (ModelState.IsValid)
            {

                if (!string.IsNullOrEmpty(Request["listSortedPageId"]))
                    chapter.ListSortedPagesId = Request["listSortedPageId"];

                _chapterRepository.InsertOrUpdate(chapter);
                return RedirectToAction("Details", new { id = chapter.Id });
            }
            return View(chapter);
        }
        [HttpPost]
        [Authorize]
        public JsonResult DeleteConfirmed(int id)
        {
           _chapterRepository.Delete(id);
            _chapterRepository.Save();
            return SuccessFeedback;
        }

        public string UploadFiles(HttpPostedFileBase fileData, FormCollection forms)
        {
            try
            {
                string savedFilename = string.Empty;
                string folder = string.Empty;
                if (!string.IsNullOrEmpty(forms.Get("path")))
                {
                    folder = forms.Get("path");
                }


                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase postedFileBase = Request.Files[file];

                    if (postedFileBase != null && postedFileBase.ContentLength > 0)
                    {
                        string filename = DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + "_" +
                                          Path.GetFileName(postedFileBase.FileName);


                        savedFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder, filename);
                        if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder)))
                            Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder));
                        postedFileBase.SaveAs(savedFilename);
                    }
                }

                return savedFilename;
            }
            catch (Exception e)
            {
                return (e.Message);
            }
        }

        [HttpPost]
        [JsonAuthentication]
        public JsonResult Like(int chapterId)
        {
            _chapterRepository.Like(chapterId, ExtendedIdentity.Id);
            ChapterLike chapterLike = _activityRepository.FindChapterLike(chapterId, ExtendedIdentity.Id);
            if (chapterLike != null)
            {
                _activityRepository.CreateActivity(chapterLike, Constant.LikedChapterType);
                _activityRepository.Save();
            }
            return SuccessFeedback;
        }

        [HttpPost]
        [JsonAuthentication]
        public ActionResult UnLike(int chapterId)
        {
            _chapterRepository.UnLike(chapterId, ExtendedIdentity.Id);
            return SuccessFeedback;
        }

        [HttpPost]
        public JsonResult ExistChapterName(string chapterName, int chapterId, int bookId)
        {
            if (!String.IsNullOrEmpty(chapterName.Trim()) && bookId != 0)
            {
                IQueryable<Chapter> chapters = _chapterRepository.All.Where(c => c.BookId == bookId);
                foreach (Chapter chapter in chapters)
                {
                    if (chapter.ChapterName.ToLower().Equals(chapterName.Trim().ToLower()) && chapter.Id != chapterId)
                    {
                        ModelState.AddModelError("ChapterName", "ChapterName already exists.");
                        return Json(new
                                        {
                                            Valid = false,
                                            Message = "ChapterName already exists."
                                        });
                    }
                }
                return Json(new
                                {
                                    Valid = true,
                                });
            }

            ModelState.AddModelError("ChapterName", "chapterName is required.");
            return Json(new
                            {
                                Valid = false,
                                Message = "chapterName is required."
                            });
        }

    }
}